package org.cqupt.content.counter.controller;

import org.cqupt.content.counter.entity.ArticleEntity;
import org.cqupt.content.counter.entity.ArticleList;
import org.cqupt.content.counter.entity.RestResult;
import org.cqupt.content.counter.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/api/counter/v1/article")
public class ArticleController {
	@Autowired
	ArticleService articleService;
	
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST)
	public RestResult<ArticleList> insert(@RequestBody ArticleEntity articleEntity,@RequestParam int page) {
		RestResult<ArticleList> restResult = new RestResult<ArticleList>();
		try {
			ArticleList date = articleService.insertOrUpdate(articleEntity, page);
			restResult.setData(date);
		} catch (Exception e) {
			restResult.setCode(-1);
			restResult.setMessage("失败:"+e.getMessage());
		}
		return restResult;
	}
	
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET)
	public RestResult<ArticleList> get(@RequestParam int index, @RequestParam int page) {
		RestResult<ArticleList> restResult = new RestResult<ArticleList>();
		ArticleList date = articleService.get(index, page);
		restResult.setData(date);
		if (date == null) {
			restResult.setCode(-1);
			restResult.setMessage("查询数据库失败");
		}
		return restResult;
	}
	
	@ResponseBody
	@RequestMapping(value = "/{articleId}", method = RequestMethod.DELETE)
	public RestResult<Integer> get(@PathVariable int articleId) {
		RestResult<Integer> restResult = new RestResult<Integer>();
		int date = articleService.delete(articleId);
		restResult.setData(date);
		if (date==0) {
			restResult.setCode(-1);
			restResult.setMessage("删除数据库失败");
		}
		return restResult;
	}

}
